package com.gridmobi.xrtb.util;

import com.alibaba.fastjson.JSONObject;
import com.gridmobi.xrtb.domain.adn.OsE;
import com.gridmobi.xrtb.domain.dsp.DspTrackLog;
import com.gridmobi.xrtb.domain.dsp.common.Patten;
import com.gridmobi.xrtb.domain.dsp.common.enums.ImpSecureE;
import com.gridmobi.xrtb.model.openrtb23.OpenRTB23BidRequest;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

/**
 * @author
 */
public class RtbUtil {

    public static DspTrackLog packTrackArgs(LocalDateTime now, Map<String, String> args, HttpServletRequest request) {
        String ip = IpUtil.getIp(request);
        args.put("ip", ip);
        String stmp = now.format(DateTimeFormatter.ofPattern(Patten.DATETIME));
        args.put("stmp", stmp);

        return JSONObject.parseObject(JSONObject.toJSONString(args), DspTrackLog.class);

    }

    public static String urlEncode(String arg) {
        try {
            return URLEncoder.encode(arg, "utf-8");
        } catch (UnsupportedEncodingException e) {
            return arg;
        }
    }


    public static String urlDecode(String arg) {
        try {
            return URLDecoder.decode(arg, "utf-8");
        } catch (UnsupportedEncodingException e) {
            return arg;
        }
    }


    public static String get23Ifa(OpenRTB23BidRequest request) {

        String deviceId = "";
        if (request.getDevice() != null) {
            deviceId = request.getDevice().getIfa();
        }
        if (StringUtils.isEmpty(deviceId)) {

            if (request.getExt() != null) {

                if (request.getExt() != null && request.getExt().getUdi() != null) {
                    //兼容smatto协议
                    deviceId = request.getExt().getUdi().getIdfa();
                    if (StringUtils.isEmpty(deviceId)) {
                        deviceId = request.getExt().getUdi().getGoogleadid();
                    }
                }

            }
        }
        if (deviceId == null) {
            return "";
        }
        return deviceId;
    }

    public static String getAlgorixIfv(OpenRTB23BidRequest request) {

        String deviceId = "";
        if (request.getDevice() != null) {
            deviceId = request.getDevice().getIdfv();
            if (StringUtils.isBlank(deviceId)){
                JSONObject ext = (JSONObject)request.getDevice().getExt();
                if (ext == null) {
                    return "";
                }
                return (String) ext.get("idfv");
            }
        }

        return deviceId;
    }

    public static String getAlgorixOaid(OpenRTB23BidRequest request) {

        String deviceId = "";
        if (request.getDevice() != null) {
            JSONObject ext = (JSONObject)request.getDevice().getExt();
            if (ext == null) {
                return "";
            }
            return (String) ext.get("oaid");
        }

        return deviceId;
    }

    public static String getAlgorixImei(OpenRTB23BidRequest request) {

        String deviceId = "";
        if (request.getDevice() != null) {
            JSONObject ext = (JSONObject)request.getDevice().getExt();
            if (ext == null) {
                return "";
            }
            return (String) ext.get("imei");
        }

        return deviceId;
    }


    public static String get23App(OpenRTB23BidRequest request) {
        String appId = "";
        if (request.getApp() != null) {
            appId = request.getApp().getBundle();
        }
        if (StringUtils.isEmpty(appId)) {
            appId = request.getApp().getName();
        }

        if (appId == null) {
            return "";
        }
        return appId;
    }

    public static String get23Country(OpenRTB23BidRequest request) {
        String country = "";
        if (request.getUser() != null && request.getUser().getGeo() != null) {
            country = request.getUser().getGeo().getCountry();
        }
        if (StringUtils.isEmpty(country) && request.getDevice().getGeo() != null) {
            country = request.getDevice().getGeo().getCountry();
        }
        if (country == null) {
            return "";
        }
        return country;
    }

    public static String get23City(OpenRTB23BidRequest request) {
        String city = "";
        if (request.getUser() != null && request.getUser().getGeo() != null) {
            city = request.getUser().getGeo().getCity();
        }
        if (StringUtils.isEmpty(city) && request.getDevice().getGeo() != null) {
            city = request.getDevice().getGeo().getCity();
        }
        if (city == null) {
            return "";
        }
        return city;
    }

    public static String get23Lang(OpenRTB23BidRequest request) {
        String lang = "";
        if (request.getDevice() != null && StringUtils.isNotBlank(request.getDevice().getLanguage())) {
            lang = request.getDevice().getLanguage();
        }
        if (StringUtils.isEmpty(lang) && request.getApp() != null && request.getApp().getContent() != null && StringUtils.isNotBlank(request.getApp().getContent().getLanguage())) {
            lang = request.getApp().getContent().getLanguage();
        }
        if (lang == null) {
            return "";
        }
        return lang;
    }

    public static String get23OS(OpenRTB23BidRequest request) {
        String os = "3";
        if (OsE.Android.key.equalsIgnoreCase(request.getDevice().getOs())) {
            os = OsE.Android.v;
        }
        if (OsE.iOS.key.equalsIgnoreCase(request.getDevice().getOs())) {
            os = OsE.iOS.v;
        }
        return os;
    }


    public static long remainSeconds() {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime end = LocalDateTime.of(now.getYear(), now.getMonth(), now.getDayOfMonth(), 23, 0, 0);
        long daysDiff = ChronoUnit.SECONDS.between(LocalDateTime.now(), end);
        return daysDiff;
    }

    public static String packCreativeUrl(int secure, String creativeUrl) {
        /**
         * 如果是我们自己的CDB 服务器 就判断是不是需要https
         */
        /**
         * 所有素材后面都加上?随机数= 这样增加不规律性 避免中间针对素材url做手脚
         */
        if (creativeUrl.indexOf("d1yjjghhud2j2j") > 0) {
            if (secure == ImpSecureE.SECURE.code) {
                String url = creativeUrl.replace(ImpSecureE.NONSECURE.name, ImpSecureE.SECURE.name);
                if(url.indexOf("?")<0){
                    url.concat("?").concat(UUID.randomUUID().toString()).concat("=");
                }
                return url;
            }

        }
        return creativeUrl;


    }

    public static String getQuerystring(String url ){
        int i  = url.indexOf("?");
        if(i>0){
            String qstr = url.substring(i+1);
            return RtbUtil.urlEncode(qstr);
        }else{
            return null;
        }


    }

    public static String concatSid(String landurl,String encodeSid ){
        int i  = landurl.indexOf("?");
        if(i>0){
            String url  = landurl.substring(0,i+1);
            return url.concat(RtbUtil.urlDecode(encodeSid)) ;
        }else{
            return null;
        }


    }


    public static void main(String[] args) {
        String url = "http://srv.tyroo.com/www/delivery/ckt.php?ad_group_id=1935&requestSource=PUBLIC&affid=24539&appId=951&gaid={IDFA}&androidId=&IDFA={IDFA}&requestId=9330875655cbd5db10eaee4594105991555914161060&subId1={CLICK_ID}&subId2={RANDOM_SUBID}&subId3=&subId4=&subId5=com.jingleMobi.apk&optionalParams=&bannerid=17837363&pkgName=1370217070";
        String s = getQuerystring(url);
        System.out.println(url.indexOf("?"));
        Random random = new Random();
        int r = random.nextInt(Integer.MAX_VALUE);
        System.out.println(r);

    }
}
